<template>
  <el-button @click="goBack">
    返回
  </el-button>
  <div class="chart-container">
    <div ref="chartRef" class="chart" />
    <div class="controls">
      <button @click="toggleTheme">切换主题</button>
      <select v-model="selectedCity" @change="updateChart">
        <option v-for="city in cities" :value="city">{{ city }}</option>
      </select>
      <select v-model="selectedType" @change="updateChart">
        <option value="district">按区域统计</option>
        <option value="room">按房型统计</option>
      </select>
      <select v-model="selectedTypeId" @change="updateChart">
        <option value="">全部类型</option>
        <option v-for="type in availableTypes" :key="type.type" :value="type.type">
          {{ type.name }}
        </option>
      </select>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import * as echarts from 'echarts/core';
import {useRouter} from "vue-router";
import {
  BarChart,
  LineChart,
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import axios from "axios";
// 注册所需的组件和图表
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer,
]);
const router = useRouter();
const chartRef = ref(null);
const chartInstance = ref(null);
const theme = ref('light');
const houseData = ref([]);
const loading = ref(true);
const selectedCity = ref('北京');
const selectedType = ref('district');
const selectedTypeId = ref('');
const availableTypes = ref([]); // 存储从房源数据中提取的类型

// 获取所有数据
const getAllData = async () => {
  try {
    loading.value = true;
    // 获取第一页数据
    const firstResponse = await axios.get('http://127.0.0.1:8000/users/house/list/');
    
    if (!firstResponse.data || !firstResponse.data.results) {
      throw new Error('数据格式不正确');
    }

    let allData = [...firstResponse.data.results];
    const pageSize = firstResponse.data.results.length;
    const totalItems = firstResponse.data.count;
    
    // 如果有多页数据，获取所有页面
    if (totalItems > pageSize) {
      const totalPages = Math.ceil(totalItems / pageSize);
      const pageRequests = [];
      
      // 创建所有页面的请求
      for (let page = 2; page <= totalPages; page++) {
        pageRequests.push(
          axios.get(`http://127.0.0.1:8000/users/house/list/?page=${page}`)
        );
      }

      // 并行获取所有页面数据
      const responses = await Promise.all(pageRequests);
      responses.forEach(response => {
        if (response.data && response.data.results) {
          allData = [...allData, ...response.data.results];
        }
      });
    }

    // 存储所有数据
    houseData.value = allData;
    console.log('获取到的总数据条数:', allData.length);

    // 从房源数据中提取唯一的 type，并构建类型数据
    const uniqueTypes = [...new Set(allData.map(item => item.type))];
    availableTypes.value = uniqueTypes
      .filter(type => type !== null && type !== undefined) // 过滤掉 null 和 undefined
      .map(type => {
        // 根据类型返回对应的名称
        let name;
        switch(type) {
          case 1:
            name = '租房';
            break;
          case 2:
            name = '二手房';
            break;
          case 3:
            name = '新房';
            break;
          case 4:
            name = '小牛公寓';
            break;
          default:
            return null; // 对于未知类型返回 null
        }
        return {
          type: type,
          name: name
        };
      })
      .filter(item => item !== null) // 过滤掉所有未知类型
      .sort((a, b) => a.type - b.type);

    console.log('从接口提取的房源类型:', availableTypes.value);

    // 更新城市列表
    const availableCities = [...new Set(allData.map(item => item.city))];
    console.log('可用城市列表:', availableCities);

    // 如果当前选中的城市不在列表中，设置为第一个可用的城市
    if (!availableCities.includes(selectedCity.value)) {
      selectedCity.value = availableCities[0];
    }

    await updateChart();
  } catch (error) {
    console.error('获取数据失败:', error);
    houseData.value = [];
    availableTypes.value = [];
  } finally {
    loading.value = false;
  }
};

// 计算属性：获取所有不重复的城市列表
const cities = computed(() => {
  if (!houseData.value.length) return [];
  
  // 使用 Set 去重，然后转为数组并按中文排序
  const uniqueCities = [...new Set(houseData.value
    .map(item => item.city)
    .filter(city => city && city.trim() !== '')
  )];
  
  // 按中文排序
  const sortedCities = uniqueCities.sort((a, b) => a.localeCompare(b, 'zh-CN'));
  console.log('排序后的城市列表:', sortedCities);
  return sortedCities;
});

// 修改处理图表数据的函数
const processChartData = () => {
  if (!houseData.value.length || !selectedCity.value) {
    console.log('数据不完整:', {
      dataLength: houseData.value.length,
      selectedCity: selectedCity.value
    });
    return null;
  }

  // 过滤选中城市和房源类型的数据
  let cityData = houseData.value.filter(house => house.city === selectedCity.value);
  
  // 根据选择的类型进行过滤
  if (selectedTypeId.value === 'unknown' || 
      selectedTypeId.value === 'unknown2' || 
      selectedTypeId.value === 'unknown3' || 
      selectedTypeId.value === 'unknown4') {
    // 过滤未知类型的数据
    cityData = cityData.filter(house => !house.type);
  } else if (selectedTypeId.value) {
    // 过滤特定类型的数据
    cityData = cityData.filter(house => house.type === Number(selectedTypeId.value));
  }

  console.log('当前筛选后的数据数量:', cityData.length);

  // 根据选择的类型返回不同的图表数据
  if (selectedType.value === 'district') {
    // 按区域统计
    const districts = [...new Set(cityData.map(house => house.district))];
    districts.sort((a, b) => a.localeCompare(b, 'zh-CN'));

    const districtPrices = districts.map(district => {
      const houses = cityData.filter(house => house.district === district);
      return {
        value: houses.length > 0 
          ? Math.round(houses.reduce((sum, house) => sum + Number(house.price), 0) / houses.length)
          : 0,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3498db' },
            { offset: 1, color: '#2980b9' }
          ])
        }
      };
    });

    return {
      xAxis: {
        type: 'category',
        data: districts,
        axisLabel: {
          color: theme.value === 'dark' ? '#fff' : '#333',
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '租金 (元/月)',
        nameTextStyle: {
          color: theme.value === 'dark' ? '#fff' : '#333'
        },
        axisLabel: {
          color: theme.value === 'dark' ? '#fff' : '#333',
          formatter: '{value} 元'
        }
      },
      series: [
        {
          type: 'bar',
          data: districtPrices,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} 元',
            color: theme.value === 'dark' ? '#fff' : '#333'
          },
          barWidth: '40%'
        }
      ],
      title: {
        text: `${selectedCity.value}各区域平均租金`,
        left: 'center',
        textStyle: {
          color: theme.value === 'dark' ? '#fff' : '#333',
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      backgroundColor: theme.value === 'dark' ? '#1f1f1f' : '#ffffff'
    };
  } else {
    // 按房型统计
    const roomTypes = ['1室', '2室', '3室', '4室+'];
    const roomPrices = roomTypes.map((type, index) => {
      const houses = cityData.filter(house => {
        if (index === 3) { // 4室+
          return house.room_count >= 4;
        }
        return house.room_count === index + 1;
      });
      
      return {
        value: houses.length > 0 
          ? Math.round(houses.reduce((sum, house) => sum + Number(house.price), 0) / houses.length)
          : 0,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3498db' },
            { offset: 1, color: '#2980b9' }
          ])
        }
      };
    });

    return {
      xAxis: {
        type: 'category',
        data: roomTypes,
        axisLabel: {
          color: theme.value === 'dark' ? '#fff' : '#333'
        }
      },
      yAxis: {
        type: 'value',
        name: '租金 (元/月)',
        nameTextStyle: {
          color: theme.value === 'dark' ? '#fff' : '#333'
        },
        axisLabel: {
          color: theme.value === 'dark' ? '#fff' : '#333',
          formatter: '{value} 元'
        }
      },
      series: [
        {
          type: 'bar',
          data: roomPrices,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} 元',
            color: theme.value === 'dark' ? '#fff' : '#333'
          },
          barWidth: '40%'
        }
      ],
      title: {
        text: `${selectedCity.value}各房型平均租金`,
        left: 'center',
        textStyle: {
          color: theme.value === 'dark' ? '#fff' : '#333',
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      backgroundColor: theme.value === 'dark' ? '#1f1f1f' : '#ffffff'
    };
  }
};

// 初始化图表
const initChart = async () => {
  if (!chartRef.value) return;

  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  chartInstance.value = echarts.init(chartRef.value, theme.value);
  
  // 确保有数据后再更新图表
  if (houseData.value.length > 0) {
    await updateChart();
  }

  window.addEventListener('resize', handleResize);
};

// 修改初始化函数
const init = async () => {
  try {
    loading.value = true;
    await getAllData(); // 只需要调用获取数据的函数
    await initChart();
  } catch (error) {
    console.error('初始化失败:', error);
  } finally {
    loading.value = false;
  }
};

// 生命周期钩子
onMounted(() => {
  init();
});

onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    window.removeEventListener('resize', handleResize);
  }
});

// 监听选中城市变化
watch(selectedCity, (newValue) => {
  if (newValue && chartInstance.value) {
    updateChart();
  }
});

// 调整图表大小
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};

// 更新图表数据
const updateChart = () => {
  if (chartInstance.value) {
    chartInstance.value.setOption(processChartData());
  }
};

// 切换主题
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
  initChart();
};
</script>

<style scoped>
.chart-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: center;
}

button, select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

button:hover, select:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}
</style>